package thesis.prototype;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TimePicker;

import java.util.ArrayList;

public class MainActivity extends Activity implements OnClickListener, OnTouchListener{	

	//Intent Code
	private final int ADD_NUMBER_INTENT = 1;
	
	//FLAGS
	private boolean contacts_populated = false;
	
	//Static Variables
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
    private int mMinute;
	static final int DATE_DIALOG_ID = 0;
	static final int TIME_DIALOG_ID = 1;
	
	//Buttons
	private Button b_main_meet; // from MAIN --> START
	private Button b_main_close; // CLOSE APPLICATION
	private Button b_start_org; //START --> ORGANIZE
	private Button b_start_back; // START --> MAIN
	private Button b_org_next; //ORG --> ORG_Members
	private Button b_org_addnumber; //ORG --> Enter number to add
	private Button b_org_cancel; //ORG --> START
	private Button b_org_prev; //ORGM --> ORG
	private Button b_orgm_next; //ORGM --> DEST
	private Button b_orgm_cancel; //ORGM --> START
	private Button b_dest_prev; //DEST --> ORG
	private Button b_dest_next; //DEST --> Send Message
	private Button b_dest_cancel; //DEST --> START
	
	//EditTexts
	private EditText e_org_date;
	private EditText e_org_time;
	
	//ArrayLists and arrays
	private ArrayList<String> arr_contacts;
	private ArrayList<String> arr_numbers;
	private String[] members;
	
	//ListViews
	private ListView l_contacts;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        arr_contacts = new ArrayList<String>();
        arr_numbers = new ArrayList<String>();
		arr_contacts.clear();
		arr_numbers.clear();
    }
	
	public void setContentView(int layoutResID){
		super.setContentView(layoutResID);
		if (layoutResID == R.layout.organize_members) populateMemberList(!contacts_populated);
		addButtonListeners();
	}
	
	// this function prepares the contacts list for initial use:
	// 1.) prepares arraylist with contacts
	// 2.) prepares listview
	protected void populateMemberList(boolean first){

		//HARDCODED SECTION
        //String[] members = getResources().getStringArray(R.array.list_members);
		
        // to get contacts in contact list
		if(first) {
			contacts_populated = true;
			ContentResolver cr = getContentResolver();
			Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
					null, null, null, null);
			if(cur.getCount() > 0)
			{
				while (cur.moveToNext())
				{
					String id = cur.getString(
							cur.getColumnIndex(ContactsContract.Contacts._ID));
					String name = cur.getString(
							cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					if (Integer.parseInt(cur.getString(cur.getColumnIndex(
							ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0 )
					{
						// QUERY PHONE HERE
						Cursor pCur = cr.query(
								ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
								null,
								ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
								new String[] {id}, null);
						while (pCur.moveToNext()) {
							// Do something with phones
							String number = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
							int type = pCur.getInt(pCur.getColumnIndex(Phone.TYPE));
							switch (type) {
							case Phone.TYPE_HOME:
								// do something
								break;
							case Phone.TYPE_MOBILE:
							case Phone.TYPE_WORK_MOBILE:
								arr_contacts.add(name + "\n(" + number + ")");
								String temp_number = "";
								for(int xx = 0; xx < number.length(); xx++)
								{
									if(number.charAt(xx) != '-')
										temp_number += number.charAt(xx);
								}
								arr_numbers.add(temp_number);
								break;
							case Phone.TYPE_WORK:
								// do something
								break;
							}

						}
						pCur.close();
					}
				}
			}
			cur.close();
		}
		
        members = new String[arr_contacts.size()];
        members = arr_contacts.toArray(members);
        
		l_contacts = (ListView) findViewById(R.id.memberlist);
        
        if (l_contacts != null) 
        {
        	l_contacts.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, members));
        	l_contacts.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        	l_contacts.setOnItemClickListener(new OnItemClickListener()
        	{
        	    public void onItemClick(AdapterView<?> parent, View view,
        	    		int position, long id)
        	    {
        	    	if(((CheckedTextView) view).isChecked())
        	    	{
        	    		//Toast.makeText(getApplicationContext(), "Removed " + ((CheckedTextView) view).getText(), Toast.LENGTH_SHORT).show();
        	    		((CheckedTextView) view).setChecked(false);
        	    	}
        	    	else
        	    	{
        	    		//Toast.makeText(getApplicationContext(), "Added " + ((CheckedTextView) view).getText(), Toast.LENGTH_SHORT).show();
        	    		((CheckedTextView) view).setSelected(true);
        	    	}
        	    }
        	});
        }
	}
	
	@SuppressWarnings("unchecked")
	protected void addNewContact(String newNumber)
	{
		arr_contacts.add("[New Number]\n"+newNumber);
		arr_numbers.add(newNumber);

		populateMemberList(false);
		
		//((ArrayAdapter<String>)(l_contacts.getAdapter())).add("[New Number]\n"+newNumber);
		((ArrayAdapter<String>)(l_contacts.getAdapter())).notifyDataSetChanged();
		
	}
	
	protected void addButtonListeners(){
		b_main_meet = (Button) findViewById(R.id.main_meet);
		b_main_close = (Button) findViewById(R.id.main_close);
		b_start_org = (Button) findViewById(R.id.start_organize);
		b_start_back = (Button) findViewById(R.id.start_back);
		b_org_next = (Button) findViewById(R.id.organize_next);
		b_org_addnumber = (Button) findViewById(R.id.organizem_addnumber);
		b_org_cancel = (Button) findViewById(R.id.organize_cancel);
		b_org_prev = (Button) findViewById(R.id.organize_prev);
		b_orgm_next = (Button) findViewById(R.id.organizem_next);
		b_orgm_cancel = (Button) findViewById(R.id.organizem_cancel);
		//b_dest_prev = (Button) findViewById(R.id.dest_prev);
		//b_dest_next = (Button) findViewById(R.id.dest_next);
		//b_dest_cancel = (Button) findViewById(R.id.dest_cancel);
		
		e_org_date = (EditText) findViewById(R.id.organize_edit_date);
		e_org_time = (EditText) findViewById(R.id.organize_edit_time);
				
		if (b_main_meet != null) b_main_meet.setOnClickListener(this);
		if (b_main_close != null) b_main_close.setOnClickListener(this);
		if (b_start_org != null) b_start_org.setOnClickListener(this);
		if (b_start_back != null) b_start_back.setOnClickListener(this);
		if (b_org_next != null) b_org_next.setOnClickListener(this);
		if (b_org_addnumber != null) b_org_addnumber.setOnClickListener(this);
		if (b_org_cancel != null) b_org_cancel.setOnClickListener(this);
		if (b_org_prev != null) b_org_prev.setOnClickListener(this);
		if (b_orgm_next != null) b_orgm_next.setOnClickListener(this);
		if (b_orgm_cancel != null) b_orgm_cancel.setOnClickListener(this);
		if (b_dest_prev != null) b_dest_prev.setOnClickListener(this);
		if (b_dest_next != null) b_dest_next.setOnClickListener(this);
		if (b_dest_cancel != null) b_dest_cancel.setOnClickListener(this);
		
		if (e_org_date != null) e_org_date.setOnTouchListener(this);
		if (e_org_time != null) e_org_time.setOnTouchListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == b_main_meet){
			setContentView(R.layout.start);
		}
		else if (v == b_main_close){
			finish();
		}
		else if (v == b_start_org){
			setContentView(R.layout.organize_members);
		}
		else if (v == b_start_back){
			setContentView(R.layout.main);
		}
		else if (v == b_org_next){
			setContentView(R.layout.dest);
		}
		else if (v == b_org_addnumber){
			
			Intent intent = new Intent(this, thesis.prototype.AddNumberDialog.class);
			startActivityForResult(intent, ADD_NUMBER_INTENT);
			
			/*
			final AlertDialog.Builder alert = new AlertDialog.Builder(this);
			final EditText input = new EditText(this);
			alert.setView(input);
			alert.setPositiveButton("Add Number", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int whichButton) {
					String value = input.getText().toString().trim();
					value = value.replaceAll("-", "");
					
					//((MainActivity)((Dialog)dialog).getOwnerActivity()).addNewContact(value);
				}
			});
			alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int whichButton) {
					dialog.cancel();
				}
			});
			alert.show();
			*/
		}
		else if (v == b_org_cancel){
			setContentView(R.layout.start);
		}
		else if (v == b_org_prev){
			setContentView(R.layout.start);
		}
		else if (v == b_orgm_next){
			setContentView(R.layout.organize);
		}
		else if (v == b_orgm_cancel){
			setContentView(R.layout.start);
		}
		else if (v == b_dest_prev){
			setContentView(R.layout.organize);
		}
		else if (v == b_dest_next){
			Dialog sendAlertDialog = this.sendAlert();
			sendAlertDialog.show();
			
		}
		else if (v == b_dest_cancel){
			setContentView(R.layout.start);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent arg1) {
		if (v == e_org_date){
			showDialog(DATE_DIALOG_ID);
		}
		if (v == e_org_time){
			showDialog(TIME_DIALOG_ID); //change to show time selector
		}
		return false;
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDisplay(DATE_DIALOG_ID);
            }
        };
        
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mHour = hourOfDay;
                    mMinute = minute;
                    updateDisplay(TIME_DIALOG_ID);
                }
            };
        
	private void updateDisplay(int ID) {
		switch (ID){
		case DATE_DIALOG_ID:
			e_org_date.setText(
	        new StringBuilder()
	                // Month is 0 based so add 1
	                .append(mMonth + 1).append("-")
	                .append(mDay).append("-")
	                .append(mYear).append(" "));
			break;
		case TIME_DIALOG_ID:
			e_org_time.setText(
			        new StringBuilder()
			                .append(pad(mHour)).append(":")
			                .append(pad(mMinute)));
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    case DATE_DIALOG_ID:
	        return new DatePickerDialog(this,
	                    mDateSetListener,
	                    mYear, mMonth, mDay);
	    case TIME_DIALOG_ID:
	    	return new TimePickerDialog(this,
	    			mTimeSetListener, mHour, mMinute, false);
	    }
	    return null;
	}
	
	private static String pad(int c) {
	    if (c >= 10)
	        return String.valueOf(c);
	    else
	        return "0" + String.valueOf(c);
	}
	
	private Dialog sendAlert(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Send meeting request to attendees?")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                setContentView(R.layout.start);
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		
		return alert;
	}

	@Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data) {     
		super.onActivityResult(requestCode, resultCode, data); 
		switch(requestCode) { 
		case (ADD_NUMBER_INTENT) :
			if (resultCode == Activity.RESULT_OK) {
				String new_num = data.getExtras().getString("thesis.prototype.AddNumberDialog.NEW_CONTACT");
				//Toast t = Toast.makeText(getApplicationContext(), new_num, Toast.LENGTH_LONG);
				//t.show();
				addNewContact(new_num);
			}
			else if (resultCode == Activity.RESULT_CANCELED)
			{
			}
			break; 
		}
	}
}
